<template>
  <div id="app">
    <el-form :inline="true" :model="formSelect" class="demo-form-inline">
      <el-form-item label="学期" prop="teamValue">
        <el-select
          size="small"
          v-model="formSelect.team"
          clearable
          @change="teamChange(formSelect.team)"
          placeholder="请选择学期"
        >
          <el-option
            v-for="item in teamData"
            :key="item.termid"
            :label="item.termName"
            :value="item.termid"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="周次" prop="weekValue">
        <el-select
          size="small"
          v-model="formSelect.week"
          clearable
          @change="weekChange(formSelect.week)"
          placeholder="请选择周次"
        >
          <el-option
            v-for="item in weekData"
            :key="item.weekId"
            :label="'第' + item.week + '周'"
            :value="item.week"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="抽查地点" prop="buildingName">
        <el-select
          size="small"
          v-model="formSelect.buildingName"
          clearable
          @change="buildChange(formSelect.buildingName)"
          placeholder="请选择抽查地点"
        >
          <el-option
            v-for="item in buildData"
            :key="item.number"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="抽查人员" prop="stuOneName">
        <el-autocomplete
          clearable
          size="small"
          class="inline-input"
          v-model="formSelect.stuOneName"
          :fetch-suggestions="querySearchAsync"
          placeholder="选择抽查人员"
        ></el-autocomplete>
      </el-form-item>
      <el-form-item>
        <el-button
          size="small"
          circle
          icon="el-icon-refresh"
          @click="resetSearch"
        ></el-button>
        <el-button
          size="small"
          @click="getDataList()"
          type="primary"
          icon="el-icon-search"
          >查询</el-button
        >
        <el-button size="small" type="success" @click="openCreateDrawer"
          >新增</el-button
        >
        <el-button size="small" type="danger" @click="deleteHandle()"
          >批量删除</el-button
        >
        <el-button size="small" @click="uploadExcel" type="primary">
          <input type="file" name id="file" style="display: none" />
          导入Excel
        </el-button>
        <el-button size="small" type="success" @click="download"
          >导出Excel</el-button
        >
        <el-button size="small" type="success" @click="shuttering"
          >下载模板</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 列表 -->
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%"
    >
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50"
      ></el-table-column>
      <el-table-column
        prop="stuOneName"
        header-align="center"
        align="center"
        label="抽查人员1"
      ></el-table-column>
      <el-table-column
        prop="stuTwoName"
        header-align="center"
        align="center"
        label="抽查人员2"
      ></el-table-column>
      <el-table-column
        prop="termName"
        header-align="center"
        align="center"
        label="学期"
      ></el-table-column>
      <el-table-column
        prop="week"
        header-align="center"
        align="center"
        label="周次"
      ></el-table-column>
      <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注"
      ></el-table-column>
      <el-table-column
        prop="buildingName"
        header-align="center"
        align="center"
        label="抽查地点"
      ></el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        label="操作"
        fixed="right"
        width="270px"
      >
        <template slot-scope="scope">
          <!-- @click="distribution()"    onclick="window.location.href = '/#/test'"-->
          <el-button
            type="primary"
            size="small"
            @click="distribution(scope.row)"
            >分配抽查寝室</el-button
          >
          <el-button
            type="success"
            size="small"
            @click="openEditDrawer(scope.row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="deleteHandle(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--  -->
    <el-pagination
      class="pagination"
      background
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <!-- 修改  抽屉页面   以下-->
    <el-drawer
      title="填写结果"
      :visible.sync="editDrawerVisable"
      direction="rtl"
      size="40%"
      @close="closeDraw"
    >
      <div class="demo-drawer__content">
        <el-form :model="editForm" label-position="right">
          <el-form-item label="学期" label-width="120px">
            <el-select
              :disabled="isUpdate"
              v-model="editForm.termName"
              clearable
              placeholder="请选择学期"
              @change="formTermChange"
            >
              <el-option
                v-for="item in teamData"
                :key="item.termid"
                :label="item.termName"
                :value="item.termid"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="周次" prop="week" label-width="120px">
            <el-select
              :disabled="isUpdate"
              v-model="editForm.week"
              clearable
              placeholder="请选择周次"
            >
              <el-option
                v-for="item in weekData"
                :key="item.weekId"
                :label="'第' + item.week + '周'"
                :value="item.week"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="抽查地点" label-width="120px">
            <el-select
              :disabled="isUpdate"
              v-model="editForm.buildingName"
              clearable
              placeholder="请选择抽查地点"
            >
              <el-option
                v-for="item in buildData"
                :key="item.number"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="抽查人员1" label-width="120px">
            <el-autocomplete
              class="input-new-tag"
              v-model="editForm.stuOneName"
              :fetch-suggestions="querySearchAsync"
              ref="saveTagInput"
              :trigger-on-focus="true"
              style="width: 220px"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="抽查人员2" label-width="120px">
            <el-autocomplete
              class="input-new-tag"
              v-model="editForm.stuTwoName"
              :fetch-suggestions="querySearchAsync"
              ref="saveTagInput"
              :trigger-on-focus="true"
              style="width: 220px"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="备注" label-width="120px">
            <el-input v-model="editForm.remark" style="width: 220px"></el-input>
          </el-form-item>
          <el-form-item style="margin-left: 55px; margin-right: 60px">
            <el-button
              size="small"
              type="primary"
              @click="isUpdate ? updateSpotPlan() : addSpotPlan()"
              >提 交</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  getSpotList,
  addSpotDetails,
  updataSpotDetails,
  deleteSpotDetails,
  excel,
  addExceldata,
  getStudentListByLikeName,
  getExcel,
  downloadWorkShuttering,
} from '../../api/src/SpotCheckPlan/SpotCheckPlan'
import {
  getWeekList,
  getTermList,
  getBuildList,
} from '../../api/src/DutyDetails/DutyDetails'

export default {
  name: 'SpotDetails',
  data() {
    return {
      // 修改
      formSelect: {
        stuOneName: '',
        stuTwoName: '',
        buildingName: '',
        remark: '',
        term: '',
        team: '',
        week: '',
      },
      isUpdate: false,
      editForm: {
        stuOneName: '',
        stuTwoName: '',
        id: '',
        termName: '',
        remark: '',
      },
      weekData: [],
      teamData: [],
      buildData: [],
      drawer: false,

      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      editDrawerVisable: false,
      createDrawerVisable: false,
      dataListLoading: false,
      dataListSelections: [],
      dynamicTags: [],
      dynamicTa: [],
      commitType: true,
      id: '',
      excelData: [],
    }
  },
  created() {
    this.getDataList()
  },
  methods: {
    // 导入Excel数据
    uploadExcel() {
      const file = document.getElementById('file')
      file.click()
      file.onchange = () => {
        if (!this.checkType(file.files[0])) {
          this.$message.error(
            '文件：' + file.files[0].name + ' 文件类型错误，请使用Excel文件'
          )
          return false
        }
        excel(file.files[0]).then((res) => {
          if (!res) {
            this.$message.error('Excel内容格式错误！请使用正确格式。')
          }
          this.processExceldata(res)
        })
      }
    },
    // 检测文件类型
    checkType(file) {
      const fileExt = file.name.split('.').pop().toLocaleLowerCase()
      const extArr = ['xlsx', 'xls', 'csv']
      return extArr.includes(fileExt)
    },
    // 格式Excel数据
    processExceldata(data) {
      for (let index = 0; index < data.length; index++) {
        const ele = data[index]
        const celldata = {
          stuOneName: ele.学生一姓名,
          stuTwoName: ele.学生二姓名,
          buildingName: ele.楼栋名称,
          remark: ele.备注,
          termName: ele.学期名称,
          week: ele.周次,
        }
        this.excelData.push(celldata)
      }
      addExceldata(this.excelData).then((res) => {
        this.excelData = []
        this.getDataList()
      })
    },
    // 导出Excel数据
    download() {
      getExcel()
    },
    //导出模板
    shuttering() {
      downloadWorkShuttering()
    },
    // 获取数据列表
    async getDataList() {
      this.dataListLoading = true
      this.dataList = []
      let parameter

      parameter =
        '?currentPage=' + this.pageIndex + '&pageSize=' + this.pageSize

      if (this.formSelect.stuOneName.length > 0) {
        parameter += '&stuOneName=' + this.formSelect.stuOneName
      }
      if (this.formSelect.buildingName.length > 0) {
        parameter += '&buidingName=' + this.formSelect.buildingName
      }
      if (this.formSelect.remark.length > 0) {
        parameter += '&remark=' + this.formSelect.remark
      }
      if (this.formSelect.week > 0) {
        parameter += '&week=' + this.formSelect.week
      }
      if (this.formSelect.team > 0) {
        parameter += '&termId=' + this.formSelect.team
      }

      // console.log('选择条件为====================》》》》》', parameter)

      await getSpotList(parameter).then((res) => {
        console.log('roleManagement::::::::>>>>', res)
        if (res.records === 0) {
          this.dataList = []
          this.totalPage = 0
        } else {
          this.dataList = res.records
          this.totalPage = res.total
        }

        this.dataListLoading = false
      })

      getBuildList().then((res) => {
        this.buildData = res
      })

      getTermList().then((res) => {
        this.teamData = res
      })

      // getTermList().then((res) => {
      //   this.teamData = res
      // })
    },
    // 清空搜索
    resetSearch() {
      this.formSelect = {
        stuOneName: '',
        buildingName: '',
        remark: '',
        team: '',
        week: '',
      }
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    //修改点击
    async openEditDrawer(row) {
      this.isUpdate = true
      this.editDrawerVisable = true
      this.editForm.id = row.id
      this.editForm.stuOneName = row.stuOneName
      this.editForm.stuTwoName = row.stuTwoName
      this.editForm.buildingName = row.buildingName
      this.editForm.week = row.week
      this.editForm.termName = row.termName
      this.editForm.remark = row.remark
    },
    // 修改提交
    async updateSpotPlan() {
      await updataSpotDetails(
        this.editForm.stuOneName,
        this.editForm.stuTwoName,
        this.editForm.id,
        this.editForm.remark
      ).then((res) => {
        this.$message.success(res)
      })
      this.getDataList()
      this.editDrawerVisable = false
    },
    // 关抽屉回调
    closeDraw() {
      this.editForm = {
        stuOneName: '',
        stuTwoName: '',
        id: '',
        termName: '',
        remark: '',
      }
    },
    async openCreateDrawer() {
      this.isUpdate = false
      this.editDrawerVisable = true
    },
    async addSpotPlan() {
      const data = await addSpotDetails({
        buildingName: this.editForm.buildingName,
        remark: this.editForm.remark,
        stuOneName: this.editForm.stuOneName,
        stuTwoName: this.editForm.stuTwoName,
        termId: this.editForm.termName,
        week: this.editForm.week,
      })
      this.$message.success('新增成功')
      // this.$message.success(data)
      this.getDataList()
      this.editDrawerVisable = false
    },
    // 跳转页面
    distribution(row) {
      //console.log(row.id)
      this.$router.push({
        path: '/test?id=' + row.id,
        // query: {
        //  row: row
        // }
      })
    },

    // 查找
    querySearchAsync(queryString, callback) {
      var list = [{}]
      var restaurants = this.restaurants

      getStudentListByLikeName(queryString).then((res) => {
        //在这里为这个数组中每一个对象加一个value字段, 因为autocomplete只识别value字段并在下拉列中显示
        for (let i of res) {
          i.value = i.userName //将想要展示的数据作为value
        }
        list = res
        callback(list)
      })
    },

    buildChange(value) {
      console.log(value)
      this.formSelect.buildingName = value
    },

    // 删除
    deleteHandle(id) {
      var ids = id
        ? [id]
        : this.dataListSelections.map((item) => {
            return item.id
          })

      ids.push(id)
      this.$confirm(`确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await deleteSpotDetails(ids).then((res) => {
            this.$message.success(res)
          })
          this.dataListSelections = []
          this.getDataList()
        })
        .catch(() => {})
    },
    // 学期进行选择
    teamChange(value) {
      this.formSelect.termid = value
      if (value.length == 0) {
        return
      }
      getWeekList(value).then((res) => {
        this.weekData = res
      })
    },
    // 周次进行选择
    weekChange(value) {
      this.formSelect.week = value
      for (var i = 0; i < this.weekData.length; i++) {
        if (this.weekData[i].week == value) {
          this.form.weekDayId = this.weekData[i].weekId
        }
      }
    },
    // 表单周次
    formTermChange(val) {
      console.log(val)
      getWeekList(val).then((res) => {
        this.weekData = res
      })
    },
  },
}
</script>

<style scoped>
.el-pagination {
  display: flex;
  white-space: nowrap;
  padding: 20px 5px;
  color: #303133;
}
</style>
